package com.woniuxy.shop.service;

import java.util.ArrayList;
import java.util.List;

import com.woniuxy.shop.dao.AdminDao;
import com.woniuxy.shop.entity.Admin;
import com.woniuxy.shop.exception.DaoException;
import com.woniuxy.shop.exception.SameAccountException;
import com.woniuxy.shop.exception.ServiceException;

/**
*@author 作者：
*version 创建时间：
*类说明：
*/
public class AdminService {
	AdminDao ad = new AdminDao();
	public void add(Admin a) {
		//先判断某个管理员角色是否存在
		try {
			//如果返回的admins长度为0，则直接添加
			if(judgeAccountrName(a.getAccount())!=0) {
				 throw new SameAccountException("账号重复");
			}
			ad.add(a);
		} catch (DaoException e) {
			throw new ServiceException("sql执行异常",e);
		}
	}
	
	/**
	 * 查询账户名是否有重复
	 * @param account
	 * @return 0表示不重复，否则都表示重复
	 */
	public int judgeAccountrName(String account) {
		List<Admin> admins=new ArrayList<>();
		try {
			admins = ad.getAdminByAct(account);
		} catch (DaoException e) {
			throw new ServiceException("sql执行异常",e);
		}
		return admins.size();
	}
	
	public List<Admin> getAdmins(){
		List<Admin> admins;
		try {
			admins = ad.getAllAdmin();
		} catch (DaoException e) {
			throw new ServiceException("sql执行异常",e);
		}
		return admins;
	}
	
	/**
	 * 根据指定ID删除管理员
	 * @param id
	 */
	public void Del(int id) {
		try {
			ad.delete(id);
		} catch (DaoException e) {
			throw new ServiceException("sql执行异常",e);
		}
	}
	
	/**
	 * 根据账号查找管理员
	 * @param account
	 * @return
	 */
	public Admin getAdmin(String account) {
		Admin a = null;
		try {
			a = ad.getAdmin(account);
		} catch (DaoException e) {
			throw new ServiceException("sql执行异常",e);
		}
		return a;
	}
	
	/**
	 * 设置当前的Ip和time
	 * @param id
	 * @param ip
	 * @param time
	 */
	public void setIpTime(int id,String ip,String time) {
		try {
			ad.updateIpTime(id, ip, time);
		} catch (DaoException e) {
			throw new ServiceException("sql执行异常",e);
		}
	}
	
	/**
	 * 根据ID查找Admin
	 * @param id
	 * @return
	 */
	public Admin getAdminById(int id) {
		Admin a;
		try {
			a = ad.getAdminById(id);
		} catch (Exception e) {
			throw new ServiceException("sql执行异常",e);
		}
		return a;
	}
	
	public void update(Admin a) {
		try {
			ad.updateAll(a);;
		} catch (DaoException e) {
			throw new ServiceException("sql执行异常",e);
		}
	}
	
	public void updatePwd(String act, String newPwd) {
		try {
			ad.updatePassword(act, newPwd);
		} catch (DaoException e) {
			throw new ServiceException("sql执行异常",e);
		}
	}
	
}
